import hashlib
import traceback
from typing import List
from werkzeug.datastructures import FileStorage
from webapp.models import Pic
from webapp.const import RedisKey
from .image_apis import upload_image_file, get_image_url, get_thumb_url
from . import cache_utils as cache
from .logs import logger


upload_status = {
    0: '失败',
    1: '成功',
    2: '跳过',
}


def single_upload(files: List[FileStorage], file_size: int, file_md5: str = None):
    img = files[0]
    thumb = files[1] if len(files) > 1 else None
    try:
        if not file_md5:
            file_bytes = img.read()
            file_md5 = hashlib.md5(file_bytes).hexdigest().lower()
            img.seek(0)
        # 根据图片md5判断是否重复
        if Pic.query.filter_by(file_hash=file_md5).first():
            status = 2
        else:
            file_name, file_suffix = img.filename.rsplit('.', maxsplit=1)
            file_suffix = file_suffix.lower()
            if file_suffix == 'jpeg':
                file_suffix = 'jpg'
            # 发送到后续步骤继续处理
            file_hash_name = f'{file_md5}.{file_suffix}'
            upload_result = upload_image_file(file_hash_name, img, thumb)
            # 存下图片基础信息
            pic_info = {
                'file_name': file_name,
                'file_hash': file_md5,
                'file_size': round(file_size / 1024, 2),
                'file_type': file_suffix,
                'width': upload_result['width'],
                'height': upload_result['height'],
                'thumb_url': get_thumb_url(file_md5),
                'image_url': get_image_url(file_hash_name),
            }
            cache.hset(RedisKey.temp_pics_hash, file_md5, pic_info)
            status = 1
    except:
        logger.error(f'image upload error {traceback.format_exc()}')
        status = 0
    img.close()
    return {'status': status, 'msg': upload_status[status]}
